﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;


public class AutoCreateMapSprite : MonoBehaviour
{

    public int width;
    public int height;

    public GameObject prefab;
}

// Custom Editor the "old" way by modifying the script variables directly.
// No handling of multi-object editing, undo, and prefab overrides!
[CustomEditor(typeof(AutoCreateMapSprite))]
[CanEditMultipleObjects]
public class AutoCreateMapSpriteEditor : Editor
{

    
    void OnEnable()
    {
       
    }


    public override void OnInspectorGUI()
    {
        AutoCreateMapSprite m = (AutoCreateMapSprite)target;

        m.width = EditorGUILayout.IntSlider("width", m.width, 0, 100);
        ProgressBar(m.width / 100.0f, "width");

        m.height = EditorGUILayout.IntSlider("height", m.height, 0, 100);
        ProgressBar(  m.height / 100.0f, "height");

        bool allowSceneObjects = !EditorUtility.IsPersistent(target);
        m.prefab = (GameObject)EditorGUILayout.ObjectField("prefabObject", m.prefab, typeof(GameObject), allowSceneObjects);


       

        if ( GUILayout.Button( "生成地图",  GUILayout.Height(100) ))
        {

            float spriteWidth = m.prefab.GetComponent<SpriteRenderer>().sprite.rect.width / 100;
            float spriteHeight = m.prefab.GetComponent<SpriteRenderer>().sprite.rect.height / 100;


            for (int x =0; x< m.width; x++)
            {
                for (int y = 0; y < m.height; y++)
                {
                    //它本身的尺寸  加倍....
                    Vector3 pos = new Vector3(spriteWidth * x , spriteHeight * y  , 0);

                    Instantiate(m.prefab, pos, m.transform.rotation ,m.gameObject.transform );
                }
            }
           // Instantiate(m.prefab ,m.gameObject.transform);
        }

        if (GUILayout.Button("清除之前的地图",  GUILayout.Height(100)))
        {
            DestroyAllChildren(m);
        }

    }


    // Custom GUILayout progress bar.
    void ProgressBar(float value, string label)
    {
        // Get a rect for the progress bar using the same margins as a textfield:
        Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField");
        EditorGUI.ProgressBar(rect, value, label);
        EditorGUILayout.Space();
    }

    void DestroyAllChildren(AutoCreateMapSprite m)
    {
        Transform[] childs = m.GetComponentsInChildren<Transform>();
        // m.gameObject.
        foreach (Transform c  in childs)
        {
            Debug.Log(c.gameObject.name);
            if (c.gameObject.name == m.gameObject.name)
                continue;
            //DestroyImmediate(c.gameObject);
            DestroyImmediate(c.gameObject);
        }
    }


}